require("../../assets/css/reset.css");
require("../../assets/css/common.css");
require("../../assets/css/normalize.css");
require("../../assets/fonts/iconfont.css");
require("./register.css");
// 获取公共js
let { $ } = require("../../utils/dom.js");
const axios = require("axios");
// 验证码

const Captcha = require("captcha-mini");
document.addEventListener("DOMContentLoaded", function () {
	//创建验证码
	// 创建一个空变量用来接验证码的值
	let codeInit = "";
	let captcha = new Captcha();
	captcha.draw($("#captcha"), (r) => {
		// 获取到的验证，转为小写字母传给codeInit
		codeInit = r.toLowerCase();
		console.log(codeInit, "验证码1");
	});
	// 点击注册验证表单
	$("#btn").addEventListener("click", function () {
		// 验证码手机号
		// 获取手机号input的内容
		let tel = $("#tel").value;
		// 验证手机号规则
		let reg =
			/^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
		if (reg.test(tel)) {
			$(".tel").textContent = "";
		} else {
			$(".tel").textContent = "手机号错误!";
			return;
		}

		// 验证码判断（检测是否人机）
		// 获取验证码输入框的值，并转换为小写
		let code = $("#code input").value.toLowerCase();
		if (code === codeInit) {
			$(".input_title .code").textContent = "";
		} else {
			$(".input_title .code").textContent = "验证码错误！";
			return;
		}
		// 输入密码检测判断
		// 获取密码框值
		let password = $("#password").value;
		const pwd = /^(?!\d+$)(?![a-zA-Z]+$)[a-zA-Z\d]{6,12}$/;
		if (pwd.test(password)) {
			$(".password").textContent = "";
		} else {
			$(".password").textContent = "格式不正确";
		}

		// 判断确认密码
		let password2 = $("#password2").value;
		if (password === password2) {
			$(".password2").textContent = "";
		} else {
			$(".password2").textContent = "密码不一致";
		}
		// 表单验证都通过提交
		axios
			.post("http://fitness.h5.itsource.cn:3701/api/user/register", {
				// 账号
				account: tel,
				// 密码
				password: password,
			})
			.then((res) => {
				//成功后执行
				if (res.data.errno === 0) {
					location.href = "./login.html";
				} else {
					$(".tel").textContent = res.data.message;
				}
			});
	});
	// 表单验证结束
	function foc() {
		$("input").forEach(function (v) {
			// 获取焦点添加样式
			v.addEventListener("focus", function () {
				$("input").forEach(function (v) {
					v.classList.remove("inputs");
				});
				v.classList.add("inputs");
			});
			// 失去焦点切换样式
			v.addEventListener("blur", function () {
				$("input").forEach(function (v) {
					v.classList.remove("inputs");
				});
			});
		});
	}
	foc();
});
